// 智能体问答系统前端应用

class QAApp {
    constructor() {
        this.socket = null;
        this.currentSessionId = null;
        this.currentTasks = [];
        this.isExecuting = false;
        this.editingTaskIndex = -1;
        
        this.init();
    }
    
    init() {
        this.initSocket();
        this.initEventListeners();
        this.updateUI();
    }
    
    initSocket() {
        this.socket = io();
        
        this.socket.on('connect', () => {
            console.log('Connected to server');
            this.updateConnectionStatus('connected');
        });
        
        this.socket.on('disconnect', () => {
            console.log('Disconnected from server');
            this.updateConnectionStatus('disconnected');
        });
        
        this.socket.on('question_analyzed', (data) => {
            this.handleQuestionAnalyzed(data);
        });
        
        this.socket.on('task_management_result', (data) => {
            this.handleTaskManagementResult(data);
        });
        
        this.socket.on('execution_started', (data) => {
            this.handleExecutionStarted(data);
        });
        
        this.socket.on('task_started', (data) => {
            this.handleTaskStarted(data);
        });
        
        this.socket.on('task_completed', (data) => {
            this.handleTaskCompleted(data);
        });
        
        this.socket.on('execution_completed', (data) => {
            this.handleExecutionCompleted(data);
        });
        
        this.socket.on('execution_failed', (data) => {
            this.handleExecutionFailed(data);
        });
    }
    
    initEventListeners() {
        // 问题输入框事件
        const questionInput = document.getElementById('question-input');
        questionInput.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'Enter') {
                this.sendQuestion();
            }
        });
        
        // 发送按钮事件
        document.getElementById('send-btn').addEventListener('click', () => {
            this.sendQuestion();
        });
    }
    
    updateConnectionStatus(status) {
        const statusElement = document.getElementById('connection-status');
        statusElement.className = `badge me-2 ${status === 'connected' ? 'bg-success' : 'bg-danger'}`;
        statusElement.textContent = status === 'connected' ? '已连接' : '已断开';
    }
    
    async sendQuestion() {
        const input = document.getElementById('question-input');
        const question = input.value.trim();
        
        if (!question) {
            this.showMessage('请输入问题', 'system');
            return;
        }
        
        // 禁用输入
        this.setInputEnabled(false);
        
        // 显示用户问题
        this.showMessage(question, 'user');
        
        // 清空输入框
        input.value = '';
        
        // 显示思考状态
        this.showTypingIndicator(true);
        
        try {
            const response = await fetch('/api/questions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    content: question
                })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                this.currentSessionId = data.session_id;
                this.showMessage('正在分析问题...', 'system');
                
                // 加入会话
                this.socket.emit('join_session', { session_id: this.currentSessionId });
            } else {
                this.showMessage(`错误: ${data.error}`, 'system');
                this.setInputEnabled(true);
            }
        } catch (error) {
            console.error('Send question error:', error);
            this.showMessage('发送问题失败，请重试', 'system');
            this.setInputEnabled(true);
        }
        
        this.showTypingIndicator(false);
    }
    
    handleQuestionAnalyzed(data) {
        const { analysis, execution_path, tasks } = data;
        
        this.showMessage(`问题分析完成：复杂度 ${analysis.complexity}，类型 ${analysis.category}`, 'system');
        
        if (execution_path === 'direct') {
            this.showMessage('这是一个简单问题，将直接执行', 'system');
            this.showExecutionControls(true);
        } else {
            this.showMessage(`生成了 ${tasks.length} 个任务，请查看任务列表`, 'system');
            this.currentTasks = tasks;
            this.updateTaskList();
            this.showExecutionControls(true);
        }
        
        this.setInputEnabled(true);
    }
    
    handleTaskManagementResult(data) {
        const { success, message, tasks } = data;
        
        this.showMessage(message, 'system');
        
        if (success && tasks) {
            this.currentTasks = tasks;
            this.updateTaskList();
        }
    }
    
    handleExecutionStarted(data) {
        this.isExecuting = true;
        this.showMessage('开始执行任务...', 'system');
        this.updateExecutionControls();
    }
    
    handleTaskStarted(data) {
        this.showMessage(`开始执行：${data.task_description}`, 'system');
        this.updateTaskStatus(data.task_id, 'running');
    }
    
    handleTaskCompleted(data) {
        this.showMessage(`任务完成：${data.result.substring(0, 100)}...`, 'system');
        this.updateTaskStatus(data.task_id, 'completed');
    }
    
    handleExecutionCompleted(data) {
        this.isExecuting = false;
        this.showMessage('所有任务执行完成！', 'system');
        this.showMessage(data.final_answer, 'ai');
        this.updateExecutionControls();
        this.setInputEnabled(true);
    }
    
    handleExecutionFailed(data) {
        this.isExecuting = false;
        this.showMessage(`执行失败：${data.error}`, 'system');
        this.updateExecutionControls();
        this.setInputEnabled(true);
    }
    
    showMessage(content, type) {
        const chatContainer = document.getElementById('chat-container');
        
        // 如果是第一条消息，清除欢迎文本
        const welcomeText = chatContainer.querySelector('.text-center');
        if (welcomeText) {
            welcomeText.remove();
        }
        
        const messageDiv = document.createElement('div');
        messageDiv.className = `message message-${type}`;
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.textContent = content;
        
        const timestampDiv = document.createElement('div');
        timestampDiv.className = 'message-timestamp';
        timestampDiv.textContent = new Date().toLocaleTimeString();
        
        messageDiv.appendChild(contentDiv);
        messageDiv.appendChild(timestampDiv);
        chatContainer.appendChild(messageDiv);
        
        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }
    
    updateTaskList() {
        const taskContainer = document.getElementById('task-container');
        
        if (this.currentTasks.length === 0) {
            taskContainer.innerHTML = `
                <div class="text-center text-muted py-5">
                    <i class="bi bi-clipboard-check display-4"></i>
                    <p class="mt-3">暂无任务</p>
                </div>
            `;
            return;
        }
        
        const tasksHtml = this.currentTasks.map((task, index) => `
            <div class="task-item task-${task.status}" data-task-id="${task.id}">
                <div class="task-header">
                    <span class="task-status status-${task.status}">
                        ${this.getStatusText(task.status)}
                    </span>
                    <div class="task-actions">
                        <button class="btn btn-outline-primary btn-xs" onclick="app.editTask(${index})">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-outline-danger btn-xs" onclick="app.deleteTask(${index})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
                <div class="task-description">${task.description}</div>
                ${task.result ? `<div class="task-result mt-2 p-2 bg-light rounded"><small>${task.result.substring(0, 200)}...</small></div>` : ''}
            </div>
        `).join('');
        
        taskContainer.innerHTML = tasksHtml;
        this.updateProgress();
    }
    
    updateTaskStatus(taskId, status) {
        const taskIndex = this.currentTasks.findIndex(task => task.id === taskId);
        if (taskIndex !== -1) {
            this.currentTasks[taskIndex].status = status;
            this.updateTaskList();
        }
    }
    
    updateProgress() {
        const completedTasks = this.currentTasks.filter(task => task.status === 'completed').length;
        const totalTasks = this.currentTasks.length;
        
        document.getElementById('task-progress').textContent = `${completedTasks}/${totalTasks}`;
        
        const progressBar = document.getElementById('progress-bar');
        const percentage = totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0;
        progressBar.style.width = `${percentage}%`;
    }
    
    getStatusText(status) {
        const statusMap = {
            'pending': '等待中',
            'running': '执行中',
            'completed': '已完成',
            'failed': '失败'
        };
        return statusMap[status] || status;
    }
    
    showExecutionControls(show) {
        const controls = document.getElementById('execution-controls');
        controls.style.display = show ? 'block' : 'none';
    }
    
    updateExecutionControls() {
        const startBtn = document.getElementById('start-execution-btn');
        const cancelBtn = document.getElementById('cancel-execution-btn');
        
        if (this.isExecuting) {
            startBtn.style.display = 'none';
            cancelBtn.style.display = 'block';
        } else {
            startBtn.style.display = 'block';
            cancelBtn.style.display = 'none';
        }
    }
    
    async startExecution() {
        if (!this.currentSessionId) {
            this.showMessage('没有活跃的会话', 'system');
            return;
        }
        
        try {
            const response = await fetch(`/api/execution/${this.currentSessionId}/start`, {
                method: 'POST'
            });
            
            const data = await response.json();
            
            if (!response.ok) {
                this.showMessage(`启动执行失败：${data.error}`, 'system');
            }
        } catch (error) {
            console.error('Start execution error:', error);
            this.showMessage('启动执行失败，请重试', 'system');
        }
    }
    
    async cancelExecution() {
        if (!this.currentSessionId) {
            return;
        }
        
        try {
            const response = await fetch(`/api/execution/${this.currentSessionId}/cancel`, {
                method: 'POST'
            });
            
            if (response.ok) {
                this.isExecuting = false;
                this.showMessage('执行已取消', 'system');
                this.updateExecutionControls();
            }
        } catch (error) {
            console.error('Cancel execution error:', error);
        }
    }
    
    editTask(index) {
        this.editingTaskIndex = index;
        const task = this.currentTasks[index];
        
        document.getElementById('task-edit-description').value = task.description;
        
        const modal = new bootstrap.Modal(document.getElementById('taskEditModal'));
        modal.show();
    }
    
    async saveTaskEdit() {
        const newDescription = document.getElementById('task-edit-description').value.trim();
        
        if (!newDescription) {
            alert('请输入任务描述');
            return;
        }
        
        const command = `修改第${this.editingTaskIndex + 1}个任务为：${newDescription}`;
        await this.sendTaskCommand(command);
        
        const modal = bootstrap.Modal.getInstance(document.getElementById('taskEditModal'));
        modal.hide();
    }
    
    async deleteTask(index) {
        if (!confirm('确定要删除这个任务吗？')) {
            return;
        }
        
        const command = `删除第${index + 1}个任务`;
        await this.sendTaskCommand(command);
    }
    
    async sendTaskCommand(command) {
        if (!this.currentSessionId) {
            return;
        }
        
        try {
            const response = await fetch(`/api/tasks/${this.currentSessionId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    command: command
                })
            });
            
            if (!response.ok) {
                const data = await response.json();
                this.showMessage(`任务操作失败：${data.error}`, 'system');
            }
        } catch (error) {
            console.error('Task command error:', error);
            this.showMessage('任务操作失败，请重试', 'system');
        }
    }
    
    setInputEnabled(enabled) {
        const input = document.getElementById('question-input');
        const button = document.getElementById('send-btn');
        
        input.disabled = !enabled;
        button.disabled = !enabled;
    }
    
    showTypingIndicator(show) {
        const indicator = document.getElementById('typing-indicator');
        indicator.style.display = show ? 'inline' : 'none';
    }
    
    clearSession() {
        this.currentSessionId = null;
        this.currentTasks = [];
        this.isExecuting = false;
        
        // 清空聊天记录
        const chatContainer = document.getElementById('chat-container');
        chatContainer.innerHTML = `
            <div class="text-center text-muted py-5">
                <i class="bi bi-chat-square-text display-4"></i>
                <p class="mt-3">请输入您的问题开始对话</p>
            </div>
        `;
        
        // 重置任务列表
        this.updateTaskList();
        
        // 隐藏执行控制
        this.showExecutionControls(false);
        
        // 重置UI状态
        this.updateUI();
        
        this.showMessage('已开始新会话', 'system');
    }
    
    updateUI() {
        this.setInputEnabled(true);
        this.showTypingIndicator(false);
        this.updateExecutionControls();
    }
}

// 全局函数（供HTML调用）
function sendQuestion() {
    app.sendQuestion();
}

function startExecution() {
    app.startExecution();
}

function cancelExecution() {
    app.cancelExecution();
}

function clearSession() {
    app.clearSession();
}

function saveTaskEdit() {
    app.saveTaskEdit();
}

// 初始化应用
let app;
document.addEventListener('DOMContentLoaded', () => {
    app = new QAApp();
});